package gov.child.util;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

/**
 * @author fzh
 * @since 2017/9/19
 */
@Component
@Scope("singleton")
public class FileSaver {

    private static Logger logger = LogManager.getLogger(FileSaver.class);

    private String pathPrefix;

    public FileSaver() {
        logger.info("---------------FileSaver initialed");

    }

    public void setPathPrefix(String pathPrefix) {
        logger.info("---------------Path prefix initialed: " + pathPrefix);
        this.pathPrefix = pathPrefix;
    }

    public String getPathPrefix() {
        return pathPrefix;
    }

    public String save(String fileName, byte[] source) throws IOException {
        String path = this.pathPrefix + File.separator + fileName;
        File file = new File(path);
        FileUtils.writeByteArrayToFile(file, source);
        logger.info("---------------Saver save a file: " + fileName + ",size: " + source.length);
        return path;
    }
}
